Skip to content

Conversation

@sunjingwen21
Copy link

问题描述

您好:
在我的使用过程中发现,当虚拟机的IP地址、端口等配置发生变化但vmid保持不变时,现有的add_host方法无法检测到配置变更,导致Prometheus服务发现无法获取最新的配置信息。

具体场景:

  • 用户修改了虚拟机的网络配置(IP地址、端口等)
  • 虚拟机的vmid没有变化
  • 按照原有逻辑,host_exists()方法会认为这是同一个host,不会更新
  • 导致Prometheus服务发现仍然使用旧的配置信息

解决方案

修改add_host方法,当发现相同vmid但配置不同的host时,自动替换旧的配置,确保服务发现始终使用最新的配置信息。

主要改进

  • 配置变更检测:使用is_same_config()方法进行配置比较,提高代码可读性
  • 自动配置更新:当vmid/type匹配但配置不同时,自动替换现有host
  • 保持唯一性约束:维持vmid/type的唯一性约束不变
  • 解决实际问题:解决IP、端口等配置变更无法被检测的问题

技术实现

def add_host(self, host: Host):
    # 检查是否存在相同 vmid 和 type 的 host
    existing_index = None
    for i, existing_host in enumerate(self.hosts):
        if existing_host.pve_type == host.pve_type and existing_host.vmid == host.vmid:
            existing_index = i
            break
    
    if existing_index is not None:
        # 如果存在,检查配置是否有变化
        existing_host = self.hosts[existing_index]
        if not existing_host.is_same_config(host):
            # 配置有变化,替换旧的
            self.hosts[existing_index] = host
            return
        else:
            # 配置相同,不需要更新
            return
    
    # 如果不存在,直接添加
    self.hosts.append(host)

测试验证

  • 手动测试配置变更场景
  • 验证去重逻辑正常工作
  • 确认配置更新功能正常
  • 测试结果显示:相同vmid但不同IP的host会被正确替换

测试输出:

sunjingwen21 and others added 3 commits August 29, 2025 09:06
@xoxys
Copy link
Member

xoxys commented Sep 18, 2025

Sorry for the delay. Ill try to look into your PR in the next days.

@sunjingwen21
Copy link
Author

Sorry for the delay. Ill try to look into your PR in the next days.抱歉耽搁了。我会在接下来的几天里查看你的 PR。

ok thanks your reply

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants